//
//  HomeViewController.m
//  LvXi_newVersion
//
//  Created by 王敏 on 16/8/10.
//  Copyright © 2016年 SJT. All rights reserved.
//

#import "HomeViewController.h"

#import "LxRoundScrollView.h"

#import "LXMallFrame.h"

#import "UIImage+LxImage.h"

#import "LXShopCartController.h"

#import "SlideView.h"

#import "PopMenu.h"

#import "LXCutscenes.h"

#import "BroadcastCell.h"

#import "ImageCell.h"

#import "HomeScrollCell.h"

#import "LXHomeButtonViewCell.h"

#import "HomeSectionHeaderView.h"

#import "SettingTableViewController.h"

#import "LXNewsListController.h"

#import "LCTabBarController.h"

#import "CategoryViewController.h"

#import "SignViewController.h"


@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,LxRoundScrollViewDelegate>{
    UIRefreshControl * _refresh;
    UIButton * _slideMenuButton;
    
    UIImageView * _floatContentImageView;
}

@property(nonatomic,strong)LxRoundScrollView * bannerView;

@property(nonatomic,strong)UITableView * tableView;

@property(nonatomic,strong)SlideView * slideView;

@property(nonatomic,strong)NSArray * flashSaleProductArray;

@property(nonatomic,strong)NSArray * indexfloorArray;

@property(nonatomic,strong)NSMutableArray * articles;

@property(nonatomic,assign)NSInteger dataLoadFlag;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataLoadFlag = 0;
    self.articles = [NSMutableArray array];
    [self setUpTableView];
    [self setUpFloatButton];
    [self.view addSubview:self.slideView];
    [self beginRefresh];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.delegate = (id)self.navigationController;
    [self setUpNavi];
    [self.bannerView startTimer];
    [self.slideView upDate];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNoticeStartTimerNotification object:nil];
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.bannerView stopTimer];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNoticeStopTimerNotification object:nil];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

-(void)setUpNavi{
    UINavigationBar * navigationBar = self.navigationController.navigationBar;
    navigationBar.translucent = YES;
    //设置导航栏背景图片
    UIImage * backgroundImage = [UIImage imageNamed:@"nav_bg"];
    UIImage * shadowImage = [UIImage imageNamed:@"nav_bg"];
    
    [navigationBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];
    [navigationBar setShadowImage:shadowImage];
}

#pragma mark - 设置悬浮按钮
-(void)setUpFloatButton{
    
    CGFloat contentWidth = ScreenWidth /12.0;
    CGFloat contentHeight = contentWidth * 2;
    
    _floatContentImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.height*0.5 - contentHeight, contentWidth, contentHeight)];
    _floatContentImageView.image = [UIImage imageNamed:@"more_option_bg"];
    _floatContentImageView.userInteractionEnabled = YES;
    [self.view addSubview:_floatContentImageView];
    
    UIButton * slideMenuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [slideMenuButton setBackgroundImage:[UIImage imageNamed:@"more_option"] forState:UIControlStateNormal];

    slideMenuButton.width = contentWidth*0.8;
    slideMenuButton.height = contentHeight*0.5;
    slideMenuButton.x = (contentWidth - slideMenuButton.width)*0.5 - 2;
    slideMenuButton.y = (contentHeight - slideMenuButton.height)*0.5;

    [slideMenuButton addTarget:self action:@selector(slideMenuButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_floatContentImageView addSubview:slideMenuButton];
    _slideMenuButton = slideMenuButton;
}


#pragma mark - 侧滑悬浮按钮点击
-(void)slideMenuButtonClick:(UIButton*)button{
    [self.slideView show];
}


#pragma mark - 初始化tableView
-(void)setUpTableView{
    UITableView * tableView = [[UITableView alloc] initWithFrame:(CGRect){0,-64,ScreenWidth,ScreenHeight} style:UITableViewStyleGrouped];
    self.tableView = tableView;
    [self.view addSubview:tableView];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.sectionFooterHeight = 0;
    tableView.sectionHeaderHeight = 0;
    tableView.backgroundColor = [UIColor clearColor];
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    LxRoundScrollView * bannerView = [[LxRoundScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth/Ratio_home_banner)];
    bannerView.delegate = self;
    self.bannerView = bannerView;
    [bannerView upDataImages];
    tableView.tableHeaderView = bannerView;

    
    MJRefreshNormalHeader * refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(beginRefresh)];
    tableView.mj_header = refreshHeader;
}

-(void)beginRefresh{
    [self loadFlashSaleData];
    [self loadOtherData];
}

-(void)endRefresh{
    [self.tableView.mj_header endRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 加载限时抢购cell数据
-(void)loadFlashSaleData{
    [[LXDataManager manager] getFlashSaleWithComplete:^(BOOL success, id res) {
        if(success){
            self.flashSaleProductArray = res;
            [self.tableView reloadData];
            self.dataLoadFlag|=(0x1<<1);
        }else{
            self.dataLoadFlag|=(0x1<<1);
            [self.tableView reloadData];
        }
    }];
}


#pragma mark - 加载其余数据
-(void)loadOtherData{
    [[LXDataManager manager] getIndexfloorWithComplete:^(BOOL success, id res) {
        if(success){
            self.indexfloorArray = res;
            self.dataLoadFlag|=(0x1<<2);
            
            [[LXDataManager manager] getArticleListWithComplete:^(BOOL success, id res) {
                if(success){
                    [self.articles removeAllObjects];
                    for (ArticleModel * ac in res) {
                        [self.articles addObject:ac.title];
                    }
                    [self.tableView reloadData];
                }
            }];
        }else{
            self.dataLoadFlag|=(0x1<<2);

        }
    }];
    //MARK:获取分类数据
    [[LXDataManager manager] getCategoryWithComplete:^(BOOL success, id res) {
        if(success){
            self.dataLoadFlag|=(0x1<<3);
        }else{
            self.dataLoadFlag|=(0x1<<3);
        }
    }];

}

#pragma mark - banner代理
-(void)LxRoundScrollView:(LxRoundScrollView *)roundScrollView didEndUpDateImages:(NSArray *)images{
    self.dataLoadFlag|=0x1;
}

-(void)setDataLoadFlag:(NSInteger)dataLoadFlag{
    _dataLoadFlag = dataLoadFlag;
    if(_dataLoadFlag == 0xf){

    }
    [self endRefresh];
    _dataLoadFlag = 0x0;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(self.indexfloorArray){
         return 3+[self.indexfloorArray[0] count];
    }else{
        return 0;
    }
   
}


//MARK:分组行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section ==0||section ==1 ||section ==2){
        return 1;
    }else{
        return 2;
    }
}


//MARK:绘制cell
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section ==0){
        LXHomeButtonViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LXHomeButtonViewCell"];
        if(!cell){
            cell = [[LXHomeButtonViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"LXHomeButtonViewCell"];
        }
        cell.handleEnevts = ^(NSString * cat_id){
            if(cat_id){
                CategoryViewController * vc = [[CategoryViewController alloc] initWithCat_id:cat_id];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                SignViewController * vc = [[SignViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
        };
        [self addCellHeight:cell.cellHeight indexPath:indexPath];
        return cell;
    }
    if(indexPath.section == 1){
        BroadcastCell * cell = [[UINib nibWithNibName:@"HomeTableViewCell" bundle:nil] instantiateWithOwner:nil options:nil][0];
        
        cell.broadcastView.messeges = self.articles;
        [self addCellHeight:cell.cellHeight indexPath:indexPath];
        return cell;
    }
   else if(indexPath.section==2){
        HomeScrollCell * cell = [[UINib nibWithNibName:@"HomeTableViewCell" bundle:nil] instantiateWithOwner:nil options:nil][2];
        cell.models = self.flashSaleProductArray;
       if([cell.models count]!=0){
           [self addCellHeight:cell.cellHeight indexPath:indexPath];
       }
       else{
           [self addCellHeight:0 indexPath:indexPath];
       }
        return cell;

    }
   else{
       if(indexPath.row==0){
           ImageCell * cell = [[UINib nibWithNibName:@"HomeTableViewCell" bundle:nil] instantiateWithOwner:nil options:nil][1];
           if(self.indexfloorArray){
               AdvPicModel * adv = self.indexfloorArray[0][indexPath.section-3];
               [cell.cellImage sd_setImageWithURL:[NSURL URLWithString:adv.pic] placeholderImage:nil];
           }
           [self addCellHeight:cell.cellHeight indexPath:indexPath];
           return cell;

       }else{
           HomeScrollCell * cell = [[UINib nibWithNibName:@"HomeTableViewCell" bundle:nil] instantiateWithOwner:nil options:nil][2];
           if(self.indexfloorArray){
               cell.models = self.indexfloorArray[1][indexPath.section-3];
           }
           
           [self addCellHeight:cell.cellHeight indexPath:indexPath];
           return cell;
       }
       
   }
    
}

//MARK:分组头部视图
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section == 0||section==1)return nil;
    HomeSectionHeaderView * header = [[HomeSectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 25.f)];
    if(section == 2){
        header.titleLabel.text = @"限时抢购";
        [header setNeedsLayout];
    }
    else{
        if(self.indexfloorArray){
            AdvPicModel * adv = self.indexfloorArray[0][section-3];
            header.titleLabel.text = adv.cat_name;
            [header setNeedsLayout];
        }
    }
    
    return header;
}

//MARK:分组底部视图
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    v.backgroundColor = [UIColor whiteColor];
    return v;
}

//MARK:分组头部视图高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0||section==1){
        return 0;
    }
    if(self.flashSaleProductArray.count!=0){
        return 25.f;
    }else{
        if(section == 1){
            return 0;
        }else{
            return 25.f;
        }
    }
    return 25.f;
}

//MARK:分组底部视图高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

//MARK:cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self cellHeightForIndexPath:indexPath];
}

//MARK:cell选中回调
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1){
        LXNewsListController * vc = [[LXNewsListController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


//MARK:侧滑view
-(SlideView*)slideView{
    WeakSelf(ws);
    __block UIButton * wsbtn  = _slideMenuButton;
    __block UIImageView * wsimgv  = _floatContentImageView;
    if(_slideView == nil){
        _slideView= [SlideView slideView];
        
        //MARK:开始显示Block
        _slideView.beginShowBlock = ^(){
            ws.navigationController.navigationBar.hidden = YES;
            LCTabBarController * tbvc = (LCTabBarController*)ws.navigationController.tabBarController;
            tbvc.tabBarHidden = YES;
            wsimgv.x = ws.slideView.containerView.width;
            [wsimgv removeFromSuperview];
            [ws.slideView.containerView addSubview:wsimgv];
        };
        //MARK:显示完成Block
        _slideView.showCompleteBlock = ^(){
            wsbtn.transform = CGAffineTransformRotate(wsbtn.transform, M_PI);
        };
        
        //MARK:开始隐藏
        _slideView.beginHiddenBlock = ^(){
            ws.navigationController.navigationBar.hidden = NO;
            LCTabBarController * tbvc = (LCTabBarController*)ws.navigationController.tabBarController;
            tbvc.tabBarHidden = NO;
        };
        //MARK:隐藏完成
        _slideView.hiddenCompleteBlock = ^(){
            wsimgv.x = 0;
            [wsimgv removeFromSuperview];
            [ws.view addSubview:wsimgv];
            wsbtn.transform = CGAffineTransformIdentity;
        };
        
        /*
         _slideView.dragBlock = ^(CGFloat offsetx){
            if(offsetx< - ws.slideView.containerView.width * 0.3){
                wsbtn.transform = CGAffineTransformMakeRotation(-M_PI);
            }
            else{
               wsbtn.transform = CGAffineTransformRotate(wsbtn.transform, M_PI); 
            }
        };
         */
    }
    return _slideView;
}



@end




